home *** CD-ROM | disk | FTP | other *** search
/ MacAddict 84 / MacAddict_084_2003_08.iso / mac / Software / Audio & Music / Audacity 1.1.3.dmg / nyquist / nyquist.lsp < prev    next >
Lisp/Scheme  |  2002-09-16  |  49KB  |  1,523 lines

  1. ;;;
  2. ;;;   ###########################################################
  3. ;;;   ### NYQUIST-- A Language for Composition and Synthesis. ###
  4. ;;;   ###                                                     ###
  5. ;;;   ### Copyright (c) 1994 by Roger B. Dannenberg           ###
  6. ;;;   ###########################################################
  7. ;;;
  8.  
  9. ;;;   
  10. ;;;   Modifications for using Nyquist within Audacity
  11. ;;;   by Dominic Mazzoni
  12. ;;;
  13.  
  14. (prog ()
  15.    (setq lppp -12.0) (setq lpp -9.0)  (setq lp -6.0)    (setq lmp -3.0)
  16.    (setq lfff 12.0) (setq lff 9.0)  (setq lf 6.0)    (setq lmf 3.0)
  17.    (setq dB0 1.00)  (setq dB1 1.122) (setq dB10 3.1623)
  18.  
  19.    (setq s 0.25) (setq sd 0.375) (setq st (/ 0.5 3.0))
  20.    (setq i 0.5)  (setq id 0.75)  (setq it (* st 2.0))
  21.    (setq q 1.0)  (setq qd 1.5)   (setq qt (* st 4.0))
  22.    (setq h 2.0)  (setq hd 3.0)   (setq ht (* st 8.0))
  23.    (setq w 4.0)  (setq wd 6.0)   (setq wt (* st 16.0))
  24. )
  25.  
  26. (if (not (boundp '*A4-Hertz*))
  27.     (setf *A4-Hertz* 440.0))
  28.  
  29. ; next pitch, for initializations below
  30. (defun np () (incf nyq:next-pitch))
  31.  
  32. (defun set-pitch-names ()
  33.    (setq no-pitch 116.0)
  34.    ; note: 58.0 is A4 - (C0 - 1) = 69 - (12 - 1)
  35.    (setf nyq:next-pitch (- (hz-to-step *A4-Hertz*) 58.0))
  36.  
  37.    (setf nyq:pitch-names
  38.     '(c0 (cs0 df0) d0 (ds0 ef0) e0 f0 (fs0 gf0) g0 (gs0 af0) a0
  39.       (as0 bf0) b0
  40.       c1 (cs1 df1) d1 (ds1 ef1) e1 f1 (fs1 gf1) g1 (gs1 af1) a1
  41.       (as1 bf1) b1
  42.       c2 (cs2 df2) d2 (ds2 ef2) e2 f2 (fs2 gf2) g2 (gs2 af2) a2
  43.       (as2 bf2) b2
  44.       c3 (cs3 df3) d3 (ds3 ef3) e3 f3 (fs3 gf3) g3 (gs3 af3) a3
  45.       (as3 bf3) b3
  46.       c4 (cs4 df4) d4 (ds4 ef4) e4 f4 (fs4 gf4) g4 (gs4 af4) a4
  47.       (as4 bf4) b4
  48.       c5 (cs5 df5) d5 (ds5 ef5) e5 f5 (fs5 gf5) g5 (gs5 af5) a5
  49.       (as5 bf5) b5
  50.       c6 (cs6 df6) d6 (ds6 ef6) e6 f6 (fs6 gf6) g6 (gs6 af6) a6
  51.       (as6 bf6) b6
  52.       c7 (cs7 df7) d7 (ds7 ef7) e7 f7 (fs7 gf7) g7 (gs7 af7) a7
  53.       (as7 bf7) b7))
  54.  
  55.    (dolist (p nyq:pitch-names)
  56.      (cond ((atom p) (set p (np)))
  57.        (t (let ((pitch (np)))
  58.         (dolist (s p) (set s pitch)))))))
  59.  
  60.  
  61. (set-pitch-names)
  62.  
  63. (if (not (boundp '*DEFAULT-SOUND-SRATE*))
  64.   (setf *DEFAULT-SOUND-SRATE* 44100.0))
  65. (if (not (boundp '*DEFAULT-CONTROL-SRATE*))
  66.   (setf *DEFAULT-CONTROL-SRATE* 2205.0))
  67.  
  68. (setf *environment-variables*
  69.       '(*WARP* *SUSTAIN* *START* *LOUD* *TRANSPOSE* 
  70.     *STOP* *CONTROL-SRATE* *SOUND-SRATE*))
  71.  
  72. (setfn environment-time car)
  73. (setfn environment-stretch cadr)
  74.  
  75. ; ENVIRONMENT-MAP - map virtual time using an environment
  76. ;
  77. ;(defun environment-map (env tim)
  78. ;  (+ (environment-time env)
  79. ;     (* (environment-stretch env) tim)))
  80.  
  81.  
  82. (defun nyq:the-environment () (mapcar 'eval *environment-variables*))
  83.  
  84.  
  85. ;; GLOBAL ENVIRONMENT VARIABLES and their startup values:
  86. (defun nyq:environment-init ()
  87.   (setq *WARP*        '(0.0 1.0 nil))
  88.   (setq *LOUD*    0.0)   ; now in dB
  89.   (setq *TRANSPOSE*    0.0)
  90.   (setq *SUSTAIN*            1.0)
  91.   (setq *START*       MIN-START-TIME)
  92.   (setq *STOP*        MAX-STOP-TIME)
  93.   (setq *CONTROL-SRATE*  *DEFAULT-CONTROL-SRATE*)
  94.   (setq *SOUND-SRATE* *DEFAULT-SOUND-SRATE*)
  95.   t)                ; return nothing in particular
  96.  
  97. (nyq:environment-init)
  98.  
  99. (defun get-duration (dur)
  100.   (- (local-to-global (* (get-sustain) dur))
  101.      (setf *rslt* (local-to-global 0))))
  102.  
  103.  
  104. (defun get-loud ()
  105.   (cond ((numberp *loud*) *loud*)
  106.     ((soundp *loud*)
  107.      (sref *loud* 0))
  108.     (t
  109.      (error (format t "*LOUD* should be a number or sound: ~A" *LOUD*)))))
  110.  
  111.  
  112. (defun get-sustain ()
  113.   (cond ((numberp *SUSTAIN*) *SUSTAIN*)
  114.     ((soundp *SUSTAIN*)
  115.      ;(display "get-sustain: lookup " (local-to-global 0) 0))
  116.      (sref *SUSTAIN* 0))
  117.     (t
  118.      (error (format t "*SUSTAIN* should be a number or sound: ~A" *SUSTAIN*)))))
  119.  
  120.  
  121. (defun get-tempo ()
  122.   (slope (snd-inverse (get-warp) (local-to-global 0)
  123.               *control-srate*)))
  124.  
  125. (defun get-transpose ()
  126.   (cond ((numberp *TRANSPOSE*) *TRANSPOSE*)
  127.     ((soundp *TRANSPOSE*)
  128.      ; (display "get-transpose: lookup " 0)
  129.      ; (format t "samples: ~A~%" (snd-samples *TRANSPOSE* 100))
  130.      (sref *TRANSPOSE* 0))
  131.     (t
  132.      (error (format t "*TRANSPOSE* should be a number or sound: ~A" *TRANSPOSE*)))))
  133.  
  134.  
  135. (defun get-warp ()
  136.   (let ((f (warp-function *WARP*)))
  137.     (cond ((null f) (error "Null warp function"))
  138.     (t
  139.      (shift-time (scale-srate f (/ (warp-stretch *WARP*)))
  140.              (- (warp-time *WARP*)))))))
  141.  
  142.  
  143. ;;;;;;;;;;;;;;;;;;;;;;
  144. ;; OSCILATORS
  145. ;;;;;;;;;;;;;;;;;;;;;;
  146.  
  147. (defun build-harmonic (n table-size) (snd-sine 0 n table-size 1))
  148.  
  149. (setf *SINE-TABLE* (list (build-harmonic 1 2048)
  150.              (hz-to-step 1.0)
  151.              T))
  152. (setf *TABLE* *SINE-TABLE*)
  153.  
  154.  
  155. ;; AMOSC
  156. ;;
  157. (defun amosc (pitch modulation &optional (sound *table*) (phase 0.0))
  158.   (let ((modulation-srate (snd-srate modulation))
  159.     (hz (step-to-hz (+ pitch (get-transpose)))))
  160.     (cond ((> *SOUND-SRATE* modulation-srate)
  161.        (setf modulation (snd-up *SOUND-SRATE* modulation)))
  162.       ((< *SOUND-SRATE* modulation-srate)
  163.        (format t "Warning: down-sampling AM modulation in amosc~%")
  164.        (setf modulation (snd-down *SOUND-SRATE* modulation))))
  165.     (cond ((> hz (/ *SOUND-SRATE* 2))
  166.        (format t "Warning: amosc frequency (~A hz) will alias at current sample rate (~A hz).\n"
  167.            hz *SOUND-SRATE*)))
  168.     (scale-db (get-loud)
  169.       (snd-amosc
  170.     (car sound)    ; samples for table
  171.     (cadr sound)    ; step represented by table
  172.     *SOUND-SRATE*    ; output sample rate
  173.     hz        ;  output hz
  174.     (local-to-global 0)    ; starting time
  175.     modulation    ; modulation
  176.     phase))))    ; phase
  177.  
  178.  
  179. ;; FMOSC
  180. ;;
  181. ;; modulation rate must be less than or equal to sound-srate, so
  182. ;; force resampling and issue a warning if necessary. snd-fmosc can
  183. ;; handle upsampling cases internally.
  184. ;;
  185. (defun fmosc (pitch modulation &optional (sound *table*) (phase 0.0))
  186.   (let ((modulation-srate (snd-srate modulation))
  187.         (hz (step-to-hz (+ pitch (get-transpose)))))
  188.     (cond ((< *SOUND-SRATE* modulation-srate)
  189.        (format t "Warning: down-sampling FM modulation in fmosc~%")
  190.        (setf modulation (snd-down *SOUND-SRATE* modulation))))
  191.     (cond ((> hz (/ *SOUND-SRATE* 2))
  192.        (format t "Warning: fmosc nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  193.            hz *SOUND-SRATE*)))
  194.     (scale-db (get-loud)
  195.       (snd-fmosc 
  196.         (car sound)        ; samples for table
  197.         (cadr sound)        ; step represented by table
  198.         *SOUND-SRATE*        ; output sample rate
  199.         hz            ;  output hz
  200.         (local-to-global 0)    ; starting time
  201.         modulation        ; modulation
  202.         phase))))        ; phase
  203.  
  204.  
  205. ;; BUZZ
  206. ;;
  207. ;; (ARGUMENTS ("long" "n") ("rate_type" "sr") ("double" "hz")
  208. ;;            ("time_type" "t0") ("sound_type" "s_fm"))
  209. ;; 
  210. (defun buzz (n pitch modulation)
  211.   (let ((modulation-srate (snd-srate modulation))
  212.         (hz (step-to-hz (+ pitch (get-transpose)))))
  213.     (cond ((< *SOUND-SRATE* modulation-srate)
  214.            (format t "Warning: down-sampling modulation in buzz~%")
  215.            (setf modulation (snd-down *SOUND-SRATE* modulation))))
  216.     (cond ((> hz (/ *SOUND-SRATE* 2))
  217.            (format t "Warning: buzz nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  218.                    hz *SOUND-SRATE*)))
  219.     (setf n (min n 1)) ; avoid divide by zero problem
  220.     (scale-db (get-loud)
  221.               (snd-buzz n                   ; number of harmonics
  222.                         *SOUND-SRATE*       ; output sample rate
  223.                         hz                  ; output hz
  224.                         (local-to-global 0) ; starting time
  225.                         modulation))))      ; freq. modulation
  226.                         
  227.  
  228. ;; (HZOSC hz [table [phase]])
  229. ;;
  230. ;; similar to FMOSC, but without "carrier" frequency parameter
  231. ;; also, hz may be a scalar or a sound
  232. ;;
  233. (defun hzosc (hz &optional (sound *table*) (phase 0.0))
  234.   (let (hz-srate)
  235.     (cond ((numberp hz)
  236.            (osc (hz-to-step hz) 1.0 sound phase))
  237.           (t
  238.            (setf hz-srate (snd-srate hz))
  239.            (cond ((< *SOUND-SRATE* hz-srate)
  240.                   (format t "Warning: down-sampling hz in hzosc~%")
  241.                   (setf hz (snd-down *SOUND-SRATE* hz))))
  242.            (scale-db (get-loud)
  243.                      (snd-fmosc (car sound) ; samples for table
  244.                                 (cadr sound) ; step repr. by table
  245.                                 *SOUND-SRATE* ; output sample rate
  246.                                 0.0 ; dummy carrier
  247.                                 (local-to-global 0) ; starting time
  248.                                 hz phase))))))
  249.  
  250.  
  251. ;; (SIOSC-BREAKPOINTS tab0 t1 tab1 ... tn tabn)
  252. ;;   converts times to sample numbers
  253. ;; NOTE: time-warping the spectral envelope seems
  254. ;; like the wrong thing to do (wouldn't it be better
  255. ;; to warp the parameters that control the spectra,
  256. ;; or don't warp at all?). Nominally, a note should
  257. ;; have a "score" or local time duration equal to the
  258. ;; SUSTAIN environment variable. (When sustain is 1.0
  259. ;; and no time-warping is in effect, the duration is 1).
  260. ;; So, scale all times by
  261. ;;        (local-to-global (get-sustain))
  262. ;; so that if the final time tn = 1.0, we get a nominal
  263. ;; length note.
  264.  
  265. (defun siosc-breakpoints (breakpoints)
  266.   (display "siosc-breakpoints" breakpoints)
  267.   (prog (sample-count result (last-count 0) time-factor)
  268.     (setf time-factor
  269.       (- (local-to-global (get-sustain))
  270.          (local-to-global 0.0)))
  271.     (setf time-factor (* time-factor *SOUND-SRATE*))
  272.     (cond ((and (listp breakpoints)
  273.         (cdr breakpoints)
  274.         (cddr breakpoints)))
  275.       (t (error "SIOSC table list must have at least 3 elements")))
  276. loop
  277.     (cond ((and (listp breakpoints)
  278.            (soundp (car breakpoints)))
  279.        (push (car breakpoints) result)
  280.        (setf breakpoints (cdr breakpoints)))
  281.       (t
  282.        (error "SIOSC expecting SOUND in table list")))
  283.     (cond ((and breakpoints
  284.         (listp breakpoints)
  285.         (numberp (car breakpoints)))
  286.        (setf sample-count (truncate
  287.         (+ 0.5 (* time-factor (car breakpoints)))))
  288.        (cond ((< sample-count last-count)
  289.           (setf sample-count (1+ last-count))))
  290.        (push sample-count result)
  291.        (setf last-count sample-count)
  292.        (setf breakpoints (cdr breakpoints))
  293.        (cond (breakpoints
  294.           (go loop))))
  295.       (breakpoints
  296.        (error "SIOSC expecting number (time) in table list")))
  297.     (setf result (reverse result))
  298.     (display "siosc-breakpoints" result)
  299.     (return result)))
  300.  
  301. ;; SIOSC -- spectral interpolation oscillator
  302. ;;
  303. ;; modulation rate must be less than or equal to sound-srate, so
  304. ;; force resampling and issue a warning if necessary. snd-fmosc can
  305. ;; handle upsampling cases internally.
  306. ;;
  307. (defun siosc (pitch modulation breakpoints)
  308.   (let ((modulation-srate (snd-srate modulation))
  309.     (hz (step-to-hz (+ pitch (get-transpose)))))
  310.     (cond ((< *SOUND-SRATE* modulation-srate)
  311.        (format t "Warning: down-sampling FM modulation in siosc~%")
  312.        (setf modulation (snd-down *SOUND-SRATE* modulation))))
  313.     (cond ((> hz (/ *SOUND-SRATE* 2))
  314.        (format t "Warning: siosc nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  315.            hz *SOUND-SRATE*)))
  316.      (scale-db (get-loud)
  317.       (snd-siosc 
  318.     (siosc-breakpoints breakpoints)    ; tables
  319.     *SOUND-SRATE*        ; output sample rate
  320.     hz            ;  output hz
  321.     (local-to-global 0)    ; starting time
  322.     modulation))))        ; modulation
  323.  
  324.  
  325. ;; LFO -- freq &optional duration sound phase)
  326. ;;
  327. ;; Default duration is 1.0 sec, default sound is *TABLE*, 
  328. ;; default phase is 0.0.
  329. ;;
  330. (defun lfo (freq &optional (duration 1.0)
  331.          (sound *SINE-TABLE*) (phase 0.0))
  332.   (let ((d (get-duration duration)))
  333.     (if (minusp d) (setf d 0))
  334.     (cond ((> freq (/ *CONTROL-SRATE* 2))
  335.        (format t "Warning: lfo frequency (~A hz) will alias at current control rate (~A hz).\n"
  336.            freq *CONTROL-SRATE*)))
  337.      (snd-osc
  338.     (car sound)        ; samples for table
  339.     (cadr sound)        ; step represented by table
  340.     *CONTROL-SRATE*        ; output sample rate
  341.     freq            ; output hz
  342.     *rslt*            ; starting time
  343.     d            ; duration
  344.     phase)))        ; phase
  345.  
  346.  
  347. ;; OSC - table lookup oscillator
  348. ;;
  349. (defun osc (pitch &optional (duration 1.0) 
  350.           (sound *TABLE*) (phase 0.0))
  351.   (let ((d (get-duration duration))
  352.     (hz (step-to-hz (+ pitch (get-transpose)))))
  353.     ;(display "osc" *warp* global-start global-stop actual-dur  
  354.     ;         (get-transpose))
  355.     (cond ((> hz (/ *SOUND-SRATE* 2))
  356.        (format t "Warning: osc frequency (~A hz) will alias at current sample rate (~A hz).\n"
  357.            hz *SOUND-SRATE*)))
  358.      (set-logical-stop
  359.      (scale-db (get-loud)
  360.            (snd-osc 
  361.         (car sound)        ; samples for table
  362.         (cadr sound)        ; step represented by table
  363.         *SOUND-SRATE*        ; output sample rate
  364.         hz            ;  output hz
  365.         *rslt*            ; starting time
  366.         d            ; duration
  367.         phase))                 ; phase
  368.      duration)))
  369.  
  370.  
  371. ;; PARTIAL -- sine osc with built-in envelope scaling
  372. ;;
  373. (defun partial (steps env)
  374.   (let ((hz (step-to-hz (+ steps (get-transpose)))))
  375.     (cond ((> hz (/ *SOUND-SRATE* 2))
  376.        (format t "Warning: partial frequency (~A hz) will alias at current sample rate (~A hz).\n"
  377.            hz *SOUND-SRATE*)))
  378.     (snd-partial *sound-srate*
  379.          hz
  380.          env)))
  381.  
  382.  
  383. ;; SAMPLER -- simple attack + sustain sampler
  384. ;;
  385. (defun sampler (pitch modulation 
  386.         &optional (sample *table*) (npoints 2))
  387.   (let ((samp (car sample))
  388.     (samp-pitch (cadr sample))
  389.     (samp-loop-start (caddr sample))
  390.     (hz (step-to-hz (+ pitch (get-transpose)))))
  391.     ; make a waveform table look like a sample with no attack:
  392.     (cond ((not (numberp samp-loop-start))
  393.        (setf samp-loop-start 0.0)))
  394.     (cond ((> hz (/ *SOUND-SRATE* 2))
  395.        (format t "Warning: sampler nominal frequency (~A hz) will alias at current sample rate (~A hz).\n"
  396.            hz *SOUND-SRATE*)))
  397.     (scale-db (get-loud)
  398.        (snd-sampler 
  399.     samp        ; samples for table
  400.     samp-pitch        ; step represented by table
  401.     samp-loop-start         ; time to start loop
  402.     *SOUND-SRATE*        ; output sample rate
  403.     hz            ;  output hz
  404.     (local-to-global 0)    ; starting time
  405.     modulation        ; modulation
  406.     npoints))))        ; number of interpolation points
  407.  
  408.  
  409. ;; SINE -- simple sine oscillator
  410. ;;
  411. (defun sine (steps &optional (duration 1.0))
  412.   (let ((hz (step-to-hz (+ steps (get-transpose))))
  413.     (d (get-duration duration)))
  414.     (cond ((> hz (/ *SOUND-SRATE* 2))
  415.        (format t "Warning: sine frequency (~A hz) will alias at current sample rate (~A hz).\n"
  416.            hz *SOUND-SRATE*)))
  417.     (snd-sine *rslt* hz *sound-srate* d)))
  418.  
  419.  
  420. ;; PLUCK
  421. ;;
  422. ;; (ARGUMENTS ("double" "sr") ("double" "hz") ("time_type" "t0") 
  423. ;;            ("time_type" "d") ("double" "final_amp"))
  424. ;;
  425. (defun pluck (steps &optional (duration 1.0) (final-amp 0.001))
  426.   (let ((hz (step-to-hz (+ steps (get-transpose))))
  427.         (d (get-duration duration)))
  428.     (cond ((> hz (/ *SOUND-SRATE* 2))
  429.        (format t "Warning: pluck frequency (~A hz) will alias at current sample rate (~A hz).\n"
  430.            hz *SOUND-SRATE*)))
  431.     (snd-pluck *SOUND-SRATE* hz *rslt* d final-amp)))
  432.  
  433.  
  434.  
  435.  
  436. ;; abs-env -- restore the standard environment
  437. ;;
  438. (defmacro abs-env (s)
  439.   `(progv '(*WARP* *LOUD* *TRANSPOSE* *SUSTAIN* 
  440.         *START* *STOP* *CONTROL-SRATE* *SOUND-SRATE*)
  441.       (list '(0.0 1.0 NIL) 0.0 0.0 1.0
  442.         -1e+9 1e+9 *DEFAULT-CONTROL-SRATE* *DEFAULT-SOUND-SRATE*)
  443.       ,s))
  444.  
  445.  
  446. ; nyq:add2 - add two arguments
  447. (defun nyq:add2 (s1 s2)
  448.     (cond ((and (arrayp s1) (not (arrayp s2)))
  449.        (setf s2 (vector s2)))
  450.       ((and (arrayp s2) (not (arrayp s1)))
  451.        (setf s1 (vector s1))))
  452.     (cond ((arrayp s1)
  453.        (sum-of-arrays s1 s2))
  454.       (t
  455.        (nyq:add-2-sounds s1 s2))))
  456.  
  457.  
  458. ; (NYQ:ADD-2-SOUNDS S1 S2) - add two sound (or number) arguments
  459. (defun nyq:add-2-sounds (s1 s2)
  460.   (cond ((numberp s1)
  461.      (cond ((numberp s2)
  462.         (+ s1 s2))
  463.            (t
  464.         (snd-offset s2 s1))))
  465.     ((numberp s2)
  466.      (snd-offset s1 s2))
  467.     (t
  468.      (let ((s1sr (snd-srate s1))
  469.            (s2sr (snd-srate s2)))
  470. ;    (display "nyq:add-2-sounds" s1sr s2sr)
  471.        (cond ((> s1sr s2sr)
  472.           (snd-add s1 (snd-up s1sr s2)))
  473.          ((< s1sr s2sr)
  474.           (snd-add (snd-up s2sr s1) s2))
  475.          (t
  476.           (snd-add s1 s2)))))))
  477.  
  478.  
  479.  
  480.  
  481. (defmacro at (x s)
  482.  `(progv '(*WARP*) (list (list (+ (warp-time *WARP*) 
  483.                   (* (warp-stretch *WARP*) ,x))
  484.                    (warp-stretch *WARP*)
  485.                    (warp-function *WARP*)))
  486.       ,s))
  487.  
  488.  
  489. ;; (AT-ABS t behavior) evaluate behavior at global time t
  490. ;;
  491. ;; *WARP* is the triple (d s f) denoting the function f(st+d),
  492. ;; a mapping from local to global time.
  493. ;; We want (d' s f) such that f(s*0 + d') = t
  494. ;; (Note that we keep the same s and f, and only change the offset.
  495. ;; To eliminate the warp and stretch use "(abs-env (at t behavior))")
  496. ;; Applying the inverse of f, d' = f-1(t), or (sref (snd-inverse f ...) t)
  497. ;; Rather than invert the entire function just to evaluate at one point,
  498. ;; we use SREF-INVERSE to find d'.
  499. ;;
  500. (defmacro at-abs (x s)
  501.  `(progv '(*WARP*)
  502.      (if (warp-function *WARP*)
  503.                (list (list (sref-inverse (warp-function *WARP*) ,x)
  504.                    (warp-stretch *WARP*)
  505.                    (warp-function *WARP*)))
  506.                (list (list ,x (warp-stretch *WARP*) NIL)))
  507.      ,s))
  508.  
  509. ;; (CLIP S1 VALUE) - clip maximum amplitude to value
  510. ;
  511. (defun clip (x v)
  512.   (cond ((numberp x)
  513.      (max (min x v) (- v)))
  514.     ((arrayp x)
  515.      (let* ((len (length x))
  516.         (result (make-array len)))
  517.         (dotimes (i len)
  518.         (setf (aref result i) 
  519.               (snd-clip (aref x i) v)))
  520.         result))
  521.     (t
  522.      (snd-clip x v))))
  523.  
  524. ;; (NYQ:COERCE-TO S1 S2) - expand sound s1 to type of s2
  525. (defun nyq:coerce-to (s1 s2)
  526.   (cond ((soundp s1)
  527.      (cond ((arrayp s2)
  528.         (nyq:sound-to-array s1 (length s2)))
  529.            (t s1)))
  530.     (t s1)))
  531.  
  532.  
  533. (defmacro continuous-control-warp (beh)
  534.   `(snd-compose (warp-abs nil ,beh)
  535.         (snd-inverse (get-warp)
  536.          (local-to-global 0) *control-srate*)))
  537.  
  538. (defmacro continuous-sound-warp (beh)
  539.   `(snd-compose (warp-abs nil ,beh)
  540.         (snd-inverse (get-warp)
  541.          (local-to-global 0) *sound-srate*)))
  542.  
  543.  
  544. (defmacro control-srate-abs (r s)
  545.   `(progv '(*CONTROL-SRATE*) (list ,r)
  546.       ,s))
  547.  
  548. ; db = 20log(ratio)
  549. ; db = 20 ln(ratio)/ln(10)
  550. ; db/20 = ln(ratio)/ln(10)
  551. ; db ln(10)/20 = ln(ratio)
  552. ; e^(db ln(10)/20) = ratio
  553. ;
  554. (setf ln10over20 (/ (log 10.0) 20))
  555.  
  556. (defun db-to-linear (x) 
  557.   (cond ((numberp x)
  558.      (exp (* ln10over20 x)))
  559.     ((arrayp x)
  560.      (let* ((len (length x))
  561.         (result (make-array len)))
  562.         (dotimes (i len)
  563.         (setf (aref result i) 
  564.               (snd-exp (snd-scale ln10over20 (aref snd i)))))
  565.         result))
  566.     (t
  567.      (snd-exp (snd-scale ln10over20 x)))))
  568.  
  569.  
  570. (defun linear-to-db (x) 
  571.   (cond ((numberp x)
  572.      (/ (log (float x)) ln10over20))
  573.     ((arrayp x)
  574.      (let* ((len (length x))
  575.         (result (make-array len)))
  576.         (dotimes (i len)
  577.         (setf (aref result i) 
  578.               (snd-scale (/ 1.0 ln10over20) (snd-log (aref snd i)))))
  579.         result))
  580.     (t
  581.      (snd-scale (/ 1.0 ln10over20) (snd-log x)))))
  582.  
  583. ; sref - access a sound at a given time point
  584. ;    note that the time is transformed to global
  585. (defun sref (sound point)
  586.   (snd-sref sound (local-to-global point)))
  587.  
  588.  
  589. ; extract - start is stretched and shifted as is stop
  590. ;  result is shifted to start at local time zero
  591. (defun extract (start stop sound)
  592.   (snd-xform sound (snd-srate sound) (local-to-global 0) 
  593.          (local-to-global start) (local-to-global stop) 1.0))
  594.  
  595. (defun extract-abs (start stop sound)
  596.   (snd-xform sound (snd-srate sound) 0 start stop 1.0))
  597.      
  598.  
  599. ;(defmacro extract (start stop sound)
  600. ;  `(let ($newsound)
  601. ;     (progv '(*START* *STOP*)
  602. ;            (list (local-to-global ,start)
  603. ;          (local-to-global ,stop))
  604. ;            (setf $newsound ,sound)
  605. ;            (setf $newsound 
  606. ;                  (loud-abs 0 (cue (set-logical-stop-abs $newsound *STOP*)))))
  607. ;     $newsound))
  608.  
  609.  
  610. ;(defmacro extract-abs (start stop sound)
  611. ;  `(let ($newsound $newstart)
  612. ;     (progv '(*START* *STOP*)
  613. ;            (list ,start ,stop)
  614. ;        (setf $newstart *START*)
  615. ;            (setf $newsound ,sound)            
  616. ;            (setf $newsound (set-logical-stop-abs $newsound *STOP*)))
  617. ;     (snd-xform $newsound (snd-srate $newsound) ,start ,stop 1.0)))
  618.  
  619.  
  620. (defun local-to-global (local-time)
  621.   (let ((d (warp-time *WARP*))
  622.     (s (warp-stretch *WARP*))
  623.     (w (warp-function *WARP*))
  624.     global-time)
  625.     (setf global-time (+ (* s local-time) d))
  626.     (if w (snd-sref w global-time) global-time)))
  627.  
  628.  
  629. (defmacro loud (x s)
  630.  `(progv '(*LOUD*) (list (sum *LOUD* ,x))
  631.      ,s))
  632.  
  633.  
  634. (defmacro loud-abs (x s)
  635.  `(progv '(*LOUD*) (list ,x)
  636.      ,s))
  637.  
  638. (defun must-be-sound (x)
  639.  (cond ((soundp x) x)
  640.        (t
  641.     (error "SOUND type expected" x))))
  642.  
  643. ;; SCALE-DB -- same as scale, but argument is in db
  644. ;;
  645. (defun scale-db (factor sound)
  646.   (scale (db-to-linear factor) sound))
  647.  
  648. (defun set-control-srate (rate)
  649.   (setf *default-control-srate* (float rate))
  650.   (nyq:environment-init))
  651.  
  652. (defun set-sound-srate (rate) 
  653.   (setf *default-sound-srate* (float rate))
  654.   (nyq:environment-init))
  655.  
  656.  
  657. ; s-plot -- compute and write n data points for plotting
  658. (defun s-plot (snd &optional (n 1000))
  659.   (prog ((points (snd-samples snd (1+ n)))
  660.      (filename (soundfilename *default-plot-file*))
  661.      outf
  662.      (period (/ 1.0 (snd-srate snd)))
  663.      len 
  664.      (maximum 1.0))
  665.     (setf outf (open filename :direction :output))
  666.     (cond ((null outf)
  667.        (format t "s-plot: could not open ~A!~%" filename)
  668.        (return nil)))
  669.     (format t "s-plot: writing ~A ... ~%" filename)
  670.     (setf len (length points))
  671.     (cond ((> len n)
  672.        (setf len n)
  673.        (format t "WARNING: SOUND TRUNCATED TO ~A POINTS~%" len)))
  674.     (dotimes (i len)
  675.       (cond ((< (abs maximum) (abs (aref points i)))
  676.          (setf maximum (aref points i))))
  677.       (format outf "~A ~A~%" (* i period) (aref points i)))
  678.     (close outf)
  679.     (cond ((> (abs maximum) 1.0)
  680.        (format t "WARNING: MAXIMUM AMPLITUDE IS ~A~%" maximum)))
  681.     (format t "~A points from ~A to ~A~%"
  682.      len (snd-t0 snd) (+ (snd-t0 snd) (* len period)))))
  683.  
  684. ; run something like this to plot the points:
  685. ; graph < points.dat | plot -Ttek
  686.  
  687.  
  688. (defmacro sound-srate-abs (r s)
  689.   `(progv '(*SOUND-SRATE*) (list ,r)
  690.       ,s))
  691.  
  692.  
  693. (defmacro stretch (x s)
  694.  `(progv '(*WARP*) (list (list (warp-time *WARP*) 
  695.                    (* (warp-stretch *WARP*) ,x)
  696.                    (warp-function *WARP*)))
  697.      (if (minusp (warp-stretch *WARP*))
  698.          (break "Negative stretch factor is not allowed"))
  699.              ,s))
  700.  
  701.          
  702. (defmacro stretch-abs (x s)
  703.  `(progv '(*WARP*) (list (list (local-to-global 0)
  704.                    ,x
  705.                    nil))
  706.      (if (minusp (warp-stretch *WARP*))
  707.          (break "Negative stretch factor is not allowed"))
  708.              ,s))
  709.  
  710.  
  711. (defmacro sustain (x s)
  712.  `(progv '(*SUSTAIN*) (list (prod *SUSTAIN* ,x))
  713.       ,s))
  714.  
  715.  
  716. (defmacro sustain-abs (x s)
  717.  `(progv '(*SUSTAIN*) (list ,x)
  718.       ,s))
  719.  
  720.  
  721. ;; (WARP-FUNCTION *WARP*) - extracts function field of warp triple
  722. ;;
  723. (setfn warp-function caddr)
  724.  
  725.  
  726. ;; (WARP-STRETCH *WARP*) - extracts stretch field of warp triple
  727. ;;
  728. (setfn warp-stretch cadr)
  729.  
  730.  
  731. ;; (WARP-TIME *WARP*) - extracts time field of warp triple
  732. ;;
  733. (setfn warp-time car)
  734.  
  735.  
  736. (defmacro transpose (x s)
  737.  `(progv '(*TRANSPOSE*) (list (sum *TRANSPOSE* ,x))
  738.       ,s))
  739.  
  740.  
  741. (defmacro transpose-abs (x s)
  742.  `(progv '(*TRANSPOSE*) (list ,x)
  743.       ,s))
  744.  
  745.  
  746. ;; CONTROL-WARP -- apply a warp function to a control function
  747. ;; 
  748. (defun control-warp (warp-fn control &optional wrate)
  749.   (cond (wrate
  750.      (snd-resamplev control *control-srate*
  751.             (snd-inverse warp-fn (local-to-global 0) wrate)))
  752.     (t
  753.      (snd-compose control
  754.               (snd-inverse warp-fn (local-to-global 0) *control-srate*)))))
  755.  
  756.  
  757. ;; (cue sound)
  758. ;;    Cues the given sound; that is, it applies the current *WARP*, *LOUD*,
  759. ;; *START*, and *STOP* values to the argument.  The logical start time is at
  760. ;; local time 0.
  761. (defun cue (sound)
  762.   (cond ((arrayp sound)
  763.      (let* ((len (length sound))
  764.         (result (make-array len)))
  765.         (dotimes (i len)
  766.         (setf (aref result i)
  767.               (cue-sound (aref sound i))))
  768.         result))
  769.     (t
  770.      (cue-sound sound))))
  771.  
  772. (defun cue-sound (sound)
  773.   (snd-xform sound
  774.          (snd-srate sound)
  775.          (local-to-global 0) *START* *STOP* (db-to-linear (get-loud))))
  776.  
  777. ;; (sound sound)
  778. ;;    Same as (cue sound), except also warps the sound.
  779. ;; Note that the *WARP* can change the pitch of the
  780. ;; sound as a result of resampling.
  781. ;; Here's the derivation for the warping code:
  782. ;; *WARP* is a triple: (d s f) which denotes that the warp from local to
  783. ;; global time is: f(st+d)
  784. ;; We need to compose sound with the inverse of this to get a function
  785. ;; of global time
  786. ;; Let f-1 be the inverse of f.  Then the inverse of f(st+d) is 
  787. ;; (f-1(t) - d)/s
  788. ;; The composition gives us: (snd-compose sound (f-1(t) - d)/s)
  789. ;; Eliminate the 1/s term by changing the sample rate of sound:
  790. ;;  = (snd-compose (snd-scale-srate sound s) (f-1(t) - d))
  791. ;; Eliminate the -d term by shifting f before taking the inverse:
  792. ;;  = (snd-compose (scale-srate sound s) ((inverse f) - d))
  793. ;;  = (snd-compose (scale-srate sound s) (inverse f(t + d)))
  794. ;;  = (snd-compose (scale-srate sound s) (inverse (shift f -d)))
  795. ;; snd-inverse takes a time and sample rate.  For time, use zero.
  796. ;; The sample rate of inverse determines the final sample rate of
  797. ;; this function, so use *SOUND-SRATE*:
  798. ;;  = (snd-compose (scale-srate sound s) (snd-inverse (shift-time f (- d))
  799. ;;                                              0 *SOUND-SRATE*))
  800. ;;
  801. (defun sound (sound)
  802.    (cond ((null (warp-function *WARP*))
  803.       (snd-xform sound (/ (snd-srate sound) (warp-stretch *WARP*))
  804.              (local-to-global 0)
  805.              *START* *STOP* (db-to-linear (get-loud))))
  806.      (t
  807.       (snd-compose (scale-srate sound (warp-stretch *WARP*))
  808.                (snd-inverse (shift-time (warp-function *WARP*)
  809.                         (- (warp-time *WARP*)))
  810.                     0 *SOUND-SRATE*)))))
  811.  
  812.  
  813. ;; (SCALE-SRATE SOUND SCALE)
  814. ;; multiplies the sample rate by scale
  815. (defun scale-srate (sound scale)
  816.   (let ((new-srate (* scale (snd-srate sound))))
  817.     (snd-xform sound new-srate (snd-time sound) 
  818.            MIN-START-TIME MAX-STOP-TIME 1.0)))
  819.  
  820.  
  821. ;; (SHIFT-TIME SOUND SHIFT)
  822. ;; shift the time of a function by SHIFT, i.e. if SOUND is f(t),
  823. ;; then (shift-time SOUND SHIFT) is f(t - SHIFT).  Note that if
  824. ;; you look at plots, the shifted sound will move *right* when SHIFT
  825. ;; is positive.  
  826. (defun shift-time (sound shift)
  827.   (snd-xform sound (snd-srate sound) (+ (snd-t0 sound) shift)
  828.          MIN-START-TIME MAX-STOP-TIME 1.0))
  829.  
  830.  
  831. ;; (NYQ:SOUND-TO-ARRAY SOUND N) - duplicate SOUND to N channels
  832. ;;
  833. (defun nyq:sound-to-array (sound n)
  834.   (let ((result (make-array n)))
  835.     (dotimes (i n)
  836.       (setf (aref result i) sound))
  837.     result))
  838.  
  839.  
  840. ;; (control sound)
  841. ;;    Same as (sound sound), except this is used for control signals.  
  842. ;;    This code is identical to sound.
  843. (setfn control sound)
  844.  
  845.  
  846. ;; (env t1 t2 t4 l1 l2 l3 &optional duration)
  847. ;; Creates a 4-phase envelope.
  848. ;;    tN is the duration of phase N, and lN is the final level of
  849. ;;    phase N.  t3 is implied by the duration, and l4 is 0.0.
  850. ;;    If dur is not supplied, then 1.0 is assumed.  The envelope
  851. ;;    duration is the product of dur, *STRETCH*, and *SUSTAIN*.  If 
  852. ;;    t1 + t2 + 2ms + t4 > duration, then a two-phase envelope is
  853. ;;    substituted that has an attack/release time ratio = t1/t4.
  854. ;;    The sample rate of the returned sound is *CONTROL-SRATE*.
  855. ;;
  856. ;; Time transformation: the envelope is not warped; the start time and
  857. ;; stop times are warped to global time.  Then the value of *SUSTAIN* at
  858. ;; the begining of the envelope is used to determing absolute duration.
  859. ;; Since PWL is ultimately called to create the envelope, we must use
  860. ;; ABS-ENV to prevent any further transforms inside PWL.  We use
  861. ;; (AT global-start ...) inside ABS-ENV so that the final result has 
  862. ;; the proper starting time.
  863. ;;
  864. (defun env (t1 t2 t4 l1 l2 l3 &optional (duration 1.0))
  865.   (let (actual-dur min-dur ratio t3
  866.     (actual-dur (get-duration duration)))
  867.     (setf min-dur (+ t1 t2 t4 0.002))
  868.     (cond ((< actual-dur min-dur)
  869.        (setf ratio (/ t1 (+ t1 t4)))
  870.        (setf t1 (* ratio actual-dur))
  871.        (setf t2 (- actual-dur t1))
  872.        (setf t3 0.0)
  873.        (setf t4 0.0)
  874.        (setf l2 0.0)
  875.        (setf l3 0.0))
  876.       (t
  877.        (setf t3 (- actual-dur t1 t2 t4))))
  878.     (set-logical-stop
  879.      (abs-env (at *rslt*
  880.           (pwl t1 l1 (+ t1 t2) l2 (- actual-dur t4) l3 actual-dur)))
  881.      duration)))
  882.  
  883.  
  884. (defun gate (sound lookahead risetime falltime floor threshold)
  885.     (cond ((< lookahead risetime)
  886.            (break "lookahead must be greater than risetime in GATE function"))
  887.           ((or (< risetime 0) (< falltime 0) (< floor 0))
  888.            (break "risetime, falltime, and floor must all be positive in GATE function"))
  889.           (t
  890.            (let ((s
  891.               (snd-gate (seq (cue sound) (abs-env (s-rest lookahead)))
  892.                     lookahead risetime falltime floor threshold)))
  893.              (snd-xform s (snd-srate s) (snd-t0 sound) 
  894.             (+ (snd-t0 sound) lookahead) MAX-STOP-TIME 1.0)))))
  895.  
  896.  
  897. ;; (osc-note step &optional duration env sust volume sound)
  898. ;;   Creates a note using table-lookup osc, but with an envelope.
  899. ;; The ENV parameter may be a parameter list for the env function,
  900. ;; or it may be a sound.
  901. ;;
  902. (defun osc-note (pitch &optional (duration 1.0) 
  903.                (env-spec '(0.02 0.1 0.3 1.0 .8 .7))
  904.                (volume 0.0)
  905.                (table *TABLE*))
  906.   (set-logical-stop
  907.    (mult (loud volume (osc pitch duration table))
  908.      (if (listp env-spec)
  909.        (apply 'env env-spec)
  910.        env-spec))
  911.    duration))
  912.  
  913.  
  914. ;; force-srate -- resample snd if necessary to get sample rate
  915. ;
  916. (defun force-srate (sr snd)
  917.   (cond ((not (numberp sr))
  918.      (error "force-srate: SR should be a number")))
  919.   (cond ((arrayp snd)
  920.      (let* ((len (length snd))
  921.         (result (make-array len)))
  922.        (dotimes (i len)
  923.             (setf (aref result i) 
  924.               (force-srate sr (aref snd i))))
  925.        result))
  926.     (t
  927.      (let ((snd-sr (snd-srate snd)))
  928.        (cond ((> sr snd-sr) (snd-up sr snd))
  929.          ((< sr snd-sr) (snd-down sr snd))
  930.          (t snd))))))
  931.  
  932.  
  933. (defun force-srates (srs snd)
  934.   (cond ((and (numberp srs) (soundp snd))
  935.      (force-srate srs snd))
  936.     ((and (arrayp srs) (arrayp snd))
  937.      (let* ((len (length snd))
  938.         (result (make-array len)))
  939.        (dotimes (i len)
  940.             (setf (aref result i) 
  941.               (force-srate (aref srs i) (aref snd i))))
  942.        result))
  943.     (t (error "arguments not compatible"))))
  944.  
  945.  
  946. ;; (breakpoints-convert (t1 x1 t2 x2 ... tn) t0)
  947. ;;   converts times to sample numbers and scales amplitudes
  948. ;;   t0 is the global (after warping) start time
  949. ;;
  950. ;; NOTE: there were some stack overflow problems with the original
  951. ;; recursive version (in comments now), so it was rewritten as an
  952. ;; iteration.
  953. ;;
  954. (defun breakpoints-convert (list t0)
  955.   (prog (sample-count result sust (last-count 0))
  956.     (setf sust (get-sustain))
  957.  loop
  958.     (setf sample-count 
  959.       (truncate (+ 0.5 (* (- (local-to-global (* (car list) sust)) t0)
  960.                  *control-srate*))))
  961.     ; now we have a new sample count to put into result list
  962.     ; make sure result is non-decreasing
  963.     (cond ((< sample-count last-count)
  964.        (setf sample-count last-count)))
  965.     (setf last-count sample-count)
  966.     (push sample-count result)
  967.     (cond ((cdr list)
  968.        (setf list (cdr list))
  969.        (push (float (car list)) result)))
  970.     (setf list (cdr list))
  971.     (cond (list
  972.        (go loop)))
  973.     (return (reverse result))))
  974.  
  975.       
  976.  
  977. ;; (pwl t1 l1 t2 l2 ... tn)
  978. ;;   Creates a piece-wise linear envelope from breakpoint data.
  979. ;;
  980. (defun pwl (&rest breakpoints) (pwl-list breakpoints))
  981.  
  982. (defun pwlr (&rest breakpoints) (pwlr-list breakpoints))
  983.  
  984. ;; (breakpoints-relative list)
  985. ;;  converts list, which has the form (value dur value dur value ...)
  986. ;;  into the form (value time value time value ...)
  987. ;;  the list may have an even or odd length
  988. ;;
  989. (defun breakpoints-relative (breakpoints)
  990.   (prog (result (sum 0.0))
  991.  loop
  992.      (cond (breakpoints
  993.         (push (car breakpoints) result)
  994.         (setf breakpoints (cdr breakpoints))
  995.         (cond (breakpoints
  996.            (setf sum (+ sum (car breakpoints)))
  997.            (push sum result)
  998.            (setf breakpoints (cdr breakpoints))
  999.            (go loop)))))
  1000.      (return (reverse result))))
  1001.  
  1002.  
  1003. (defun breakpoints-relative (breakpoints)
  1004.   (prog (result (sum 0.0))
  1005.  loop
  1006.     (setf sum (+ sum (car breakpoints)))
  1007.     (push sum result)
  1008.     (cond ((cdr breakpoints)
  1009.        (setf breakpoints (cdr breakpoints))
  1010.        (push (car breakpoints) result)))
  1011.     (setf breakpoints (cdr breakpoints))
  1012.     (cond (breakpoints
  1013.        (go loop)))
  1014.     (return (reverse result))))
  1015.  
  1016.  
  1017. (defun pwlr-list (breakpoints)
  1018.   (pwl-list (breakpoints-relative breakpoints)))
  1019.  
  1020. (defun pwl-list (breakpoints)
  1021.   (let ((t0 (local-to-global 0)))
  1022.     (snd-pwl t0 *control-srate* (breakpoints-convert breakpoints t0))))
  1023.  
  1024. ;; (pwlv l1 t1 l2 t2 ... ln)
  1025. ;; Creates a piece-wise linear envelope from breakpoint data;
  1026. ;; the function initial and final values are explicit
  1027. ;;
  1028. (defun pwlv (&rest breakpoints)
  1029.   ;use pwl, modify breakpoints with initial and final changes
  1030.   ;need to put initial time of 0, and final time of 0
  1031.   (pwlv-list breakpoints))
  1032.  
  1033. (defun pwlv-list (breakpoints)
  1034.     (pwl-list (cons 0.0 (append breakpoints '(0.0)))))
  1035.  
  1036. (defun pwlvr (&rest breakpoints) (pwlvr-list breakpoints))
  1037.  
  1038. (defun pwlvr-list (breakpoints)
  1039.   (pwlr-list (cons 0.0 (append breakpoints '(0.0)))))
  1040.  
  1041. (defun pwe (&rest breakpoints)
  1042.   (pwe-list breakpoints))
  1043.  
  1044. (defun pwe-list (breakpoints)
  1045.   (pwev-list (cons 1.0 (append breakpoints '(1.0)))))
  1046.  
  1047. (defun pwer (&rest breakpoints) (pwer-list breakpoints))
  1048.  
  1049. (defun pwer-list (breakpoints)
  1050.   (pwe-list (breakpoints-relative breakpoints)))
  1051.  
  1052. (defun pwev (&rest breakpoints)
  1053.   (pwev-list breakpoints))
  1054.  
  1055. (defun pwev-list (breakpoints)
  1056.   (let ((lis (breakpoints-log breakpoints)))
  1057.     (s-exp (pwl-list lis))))
  1058.  
  1059. (defun pwevr (&rest breakpoints) (pwevr-list breakpoints))
  1060.  
  1061. (defun pwevr-list (breakpoints)
  1062.   (pwev-list (cdr (breakpoints-relative (cons 0.0 breakpoints)))))
  1063.  
  1064.  
  1065. (defun breakpoints-log (breakpoints)
  1066.   (prog ((result '(0.0)) val tim)
  1067. loop
  1068.     (cond (breakpoints
  1069.        (setf val (float (car breakpoints)))
  1070.        (setf breakpoints (cdr breakpoints))
  1071.        (cond (breakpoints
  1072.           (setf tim (car breakpoints))
  1073.           (setf breakpoints (cdr breakpoints))))
  1074.        (setf result (cons tim (cons (log val) result)))
  1075.        (cond ((null breakpoints)
  1076.           (return (reverse result))))
  1077.        (go loop))
  1078.       (t
  1079.        (error "Expected odd number of elements in breakpoint list")))))
  1080.  
  1081.  
  1082. ;; SOUND-WARP -- apply warp function to a sound
  1083. ;; 
  1084. (defun sound-warp (warp-fn signal &optional wrate)
  1085.   (cond (wrate
  1086.      (snd-resamplev signal *sound-srate*
  1087.             (snd-inverse warp-fn (local-to-global 0) wrate)))
  1088.     (t
  1089.      (snd-compose signal 
  1090.               (snd-inverse warp-fn (local-to-global 0) *sound-srate*)))))
  1091.  
  1092. (defun snd-extent (sound maxsamples) 
  1093.     (list (snd-t0 sound)
  1094.       (+ (snd-t0 sound) (/ (snd-length sound maxsamples)
  1095.                    (snd-srate sound)))))
  1096.  
  1097. (setfn snd-flatten snd-length)
  1098.  
  1099. ;; (maketable sound)
  1100. ;;   Creates a table for osc, lfo, etc. by assuming that the samples
  1101. ;;   in sound represent one period.  The sound must start at time 0.
  1102.  
  1103. (defun maketable (sound)
  1104.   (list sound
  1105.     (hz-to-step 
  1106.      (/ 1.0
  1107.         (cadr (snd-extent sound 1000000))))
  1108.     T))
  1109.  
  1110.  
  1111. ;(defmacro endTime (sound)
  1112. ;   `(get-logical-stop ,sound))
  1113.  
  1114.  
  1115. ;(defmacro beginTime (sound)
  1116. ;   `(car (snd-extent ,sound)))
  1117.  
  1118.  
  1119. ; simple stereo pan: as where goes from 0 to 1, sound
  1120. ; is linearly panned from left to right
  1121. ;
  1122. (defun pan (sound where)
  1123.   (vector (mult sound (sum 1 (mult -1 where)))
  1124.       (mult sound where)))
  1125.  
  1126.  
  1127. (defun prod (&rest snds)
  1128.   (cond ((null snds)
  1129.      (snd-zero (local-to-global 0) *sound-srate*))
  1130.     ((null (cdr snds))
  1131.      (car snds))
  1132.     ((null (cddr snds))
  1133.      (nyq:prod2 (car snds) (cadr snds)))
  1134.     (t
  1135.      (nyq:prod2 (car snds) (apply #'prod (cdr snds))))))
  1136.  
  1137. (setfn mult prod)
  1138.  
  1139.  
  1140. ;; (NYQ:PROD-OF-ARRAYS S1 S2) - form pairwise products
  1141. ;
  1142. (defun nyq:prod-of-arrays (s1 s2)
  1143.   (let* ((n (length s1))
  1144.      (p (make-array n)))
  1145.     (cond ((/= n (length s2))
  1146.        (error "unequal number of channels in prod")))
  1147.     (dotimes (i n)
  1148.       (setf (aref p i) (nyq:prod2 (aref s1 i) (aref s2 i))))
  1149.     p))
  1150.  
  1151.  
  1152. ; nyq:prod2 - multiply two arguments
  1153. (defun nyq:prod2 (s1 s2)
  1154.   (setf s1 (nyq:coerce-to s1 s2))
  1155.   (setf s2 (nyq:coerce-to s2 s1))
  1156.   (cond ((arrayp s1)
  1157.      (nyq:prod-of-arrays s1 s2))
  1158.     (t
  1159.      (nyq:prod-2-sounds s1 s2))))
  1160.  
  1161.  
  1162. ; (PROD-2-SOUNDS S1 S2) - multiply two sound arguments
  1163. (defun nyq:prod-2-sounds (s1 s2)
  1164.   (cond ((numberp s1)
  1165.      (cond ((numberp s2)
  1166.         (* s1 s2))
  1167.            (t
  1168.         (scale s1 s2))))
  1169.     ((numberp s2)
  1170.      (scale s2 s1))
  1171.     (t
  1172.      (let ((s1sr (snd-srate s1))
  1173.            (s2sr (snd-srate s2)))
  1174. ;    (display "nyq:prod-2-sounds" s1sr s2sr)
  1175.         (cond ((> s1sr s2sr)
  1176.            (snd-prod s1 (snd-up s1sr s2)))
  1177.           ((< s1sr s2sr)
  1178.            (snd-prod (snd-up s2sr s1) s2))
  1179.           (t
  1180.            (snd-prod s1 s2)))))))
  1181.  
  1182.  
  1183. ;; RAMP -- linear ramp from 0 to x
  1184. ;;
  1185. (defun ramp (&optional (x 1))
  1186.   (let* ((duration (get-duration x)))
  1187.     (warp-abs nil 
  1188.     (at *rslt*
  1189.         (sustain-abs 1
  1190.         (pwl duration 1 (+ duration (/ *control-srate*))))))))
  1191.  
  1192.  
  1193. (defun resample (snd rate)
  1194.   (cond ((arrayp snd)
  1195.      (let* ((len (length snd))
  1196.         (result (make-array len)))
  1197.         (dotimes (i len)
  1198.         (setf (aref result i)
  1199.               (snd-resample (aref snd i) rate)))
  1200.         result))
  1201.     (t
  1202.      (snd-resample snd rate))))
  1203.  
  1204.  
  1205. (defun scale (amt snd)
  1206.   (cond ((arrayp snd)
  1207.      (let* ((len (length snd))
  1208.         (result (make-array len)))
  1209.         (dotimes (i len)
  1210.         (setf (aref result i) (snd-scale amt (aref snd i))))
  1211.         result))
  1212.     (t
  1213.      (snd-scale amt snd))))
  1214.  
  1215.  
  1216. (setfn s-print-tree snd-print-tree)
  1217.  
  1218. ;; (PEAK sound-expression number-of-samples) - find peak amplitude
  1219. ;
  1220. ; NOTE: this used to be called s-max
  1221. ;
  1222. (defmacro peak (expression maxlen)
  1223.    `(snd-max ',expression ,maxlen))
  1224.  
  1225. ;; (S-MAX S1 S2) - return maximum of S1, S2
  1226. ;
  1227. (defun s-max (s1 s2)
  1228.   (setf s1 (nyq:coerce-to s1 s2))
  1229.   (setf s2 (nyq:coerce-to s2 s1))
  1230.   (cond ((arrayp s1)
  1231.      (nyq:max-of-arrays s1 s2))
  1232.     (t
  1233.      (nyq:max-2-sounds s1 s2))))
  1234.  
  1235. (defun nyq:max-of-arrays (s1 s2)
  1236.   (let* ((n (length s1))
  1237.      (p (make-array n)))
  1238.     (cond ((/= n (length s2))
  1239.        (error "unequal number of channels in max")))
  1240.     (dotimes (i n)
  1241.       (setf (aref p i) (s-max (aref s1 i) (aref s2 i))))
  1242.     p))
  1243.  
  1244. (defun nyq:max-2-sounds (s1 s2)
  1245.   (cond ((numberp s1)
  1246.          (cond ((numberp s2)
  1247.                 (max s1 s2))
  1248.                (t
  1249.                 (snd-maxv s2
  1250.                           (snd-const s1 (local-to-global 0.0)
  1251.                                      (snd-srate s2) (get-duration 1.0))))))
  1252.         ((numberp s2)
  1253.          (snd-maxv s1 (snd-const s2 (local-to-global 0.0)
  1254.                    (snd-srate s1) (get-duration 1.0))))
  1255.         (t
  1256.          (let ((s1sr (snd-srate s1))
  1257.                (s2sr (snd-srate s2)))
  1258.             (cond ((> s1sr s2sr)
  1259.                    (snd-maxv s1 (snd-up s1sr s2)))
  1260.                   ((< s1sr s2sr)
  1261.                    (snd-maxv (snd-up s2sr s1) s2))
  1262.                   (t
  1263.                    (snd-maxv s1 s2)))))))
  1264.  
  1265. (defun s-min (s1 s2)
  1266.   (setf s1 (nyq:coerce-to s1 s2))
  1267.   (setf s2 (nyq:coerce-to s2 s1))
  1268.   (cond ((arrayp s1)
  1269.          (nyq:min-of-arrays s1 s2))
  1270.         (t
  1271.          (nyq:min-2-sounds s1 s2))))
  1272.  
  1273. (defun nyq:min-of-arrays (s1 s2)
  1274.   (let* ((n (length s1))
  1275.      (p (make-array n)))
  1276.     (cond ((/= n (length s2))
  1277.        (error "unequal number of channels in max")))
  1278.     (dotimes (i n)
  1279.       (setf (aref p i) (s-min (aref s1 i) (aref s2 i))))
  1280.     p))
  1281.  
  1282. (defun nyq:min-2-sounds (s1 s2)
  1283.   (cond ((numberp s1)
  1284.      (cond ((numberp s2)
  1285.         (min s1 s2))
  1286.            (t
  1287.         (snd-minv
  1288.          (snd-const s1 (local-to-global 0.0)
  1289.                 (snd-srate s2) (get-duration 1.0))))))
  1290.     ((numberp s2)
  1291.      (snd-minv (snd-const s2 (local-to-global 0.0)
  1292.                 (snd-srate s1) (get-duration 1.0))))
  1293.     (t
  1294.      (let ((s1sr (snd-srate s1))
  1295.            (s2sr (snd-srate s2)))
  1296.         (cond ((> s1sr s2sr)
  1297.            (snd-minv s1 (snd-up s1sr s2)))
  1298.           ((< s1sr s2sr)
  1299.            (snd-minv (snd-up s2sr s1) s2))
  1300.           (t
  1301.            (snd-minv s1 s2)))))))
  1302.  
  1303. (defun snd-minv (s1 s2)
  1304.   (scale -1.0 (snd-maxv (scale -1.0 s1) (scale -1.0 s2))))
  1305.  
  1306. ; sequence macros SEQ and SEQREP are now in seq.lsp:
  1307. (load "seq" :verbose NIL)
  1308.  
  1309. ; set-logical-stop - modify the sound and return it, time is shifted and
  1310. ;             stretched
  1311. (defun set-logical-stop (snd tim)
  1312.   (let ((d (local-to-global tim)))
  1313.     (multichan-expand #'set-logical-stop-abs snd d)))
  1314.  
  1315.  
  1316. ; set-logical-stop-abs - modify the sound and return it
  1317. (defun set-logical-stop-abs (snd tim) (snd-set-logical-stop snd tim) snd)
  1318.  
  1319.  
  1320. (defmacro simrep (pair sound)
  1321.   `(let (_snds)
  1322.      (dotimes ,pair (push ,sound _snds))
  1323.      (sim-list _snds)))
  1324.  
  1325. (defun sim (&rest snds)
  1326.   (sim-list snds))
  1327.  
  1328. (setfn sum sim)
  1329.  
  1330. (defun sim-list (snds)
  1331.   (cond ((null snds)
  1332.      (snd-zero (local-to-global 0) *sound-srate*))
  1333.     ((null (cdr snds))
  1334.      (car snds))
  1335.     ((null (cddr snds))
  1336.      (nyq:add2 (car snds) (cadr snds)))
  1337.     (t
  1338.      (nyq:add2 (car snds) (sim-list (cdr snds))))))
  1339.  
  1340.  
  1341. ;(defun rest (&optional (dur 1.0))
  1342. ;  (cue (set-Logical-stop (* dur *stretch*) (s-create))))
  1343. (defun s-rest (&optional (dur 1.0))
  1344.   (let ((d (get-duration dur)))
  1345.     (snd-const 0.0 *rslt* *SOUND-SRATE* d)))
  1346.  
  1347.  
  1348. (defun tempo (warpfn)
  1349.   (slope (snd-inverse warpfn (local-to-global 0) *control-srate*)))
  1350.  
  1351.  
  1352.  
  1353. ;; (SUM-OF-ARRAYS S1 S2) - add multichannel sounds
  1354. ; result has as many channels the largest of s1, s2
  1355. ; corresponding channels are added, extras are copied
  1356. (defun sum-of-arrays (s1 s2)
  1357.   (let* ((n1 (length s1))
  1358.      (n2 (length s2))
  1359.      (n (min n1 n2))
  1360.      (m (max n1 n2))
  1361.      (result (make-array m))
  1362.      (big-s (if (> n1 n2) s1 s2)))
  1363.     
  1364.     (dotimes (i n)
  1365.       (setf (aref result i) (nyq:add-2-sounds (aref s1 i) (aref s2 i))))
  1366.     (dotimes (i (- m n))
  1367.       (setf (aref result (+ n i)) (aref big-s (+ n i))))
  1368.     result))
  1369.  
  1370.  
  1371. ;; (WARP fn behavior) - warp behavior according to fn
  1372. ;;
  1373. ;; fn is a map from behavior time to local time, and *WARP* expresses
  1374. ;; a map from local to global time.
  1375. ;; To produce a new *WARP* for the environment, we want to compose the
  1376. ;; effect of the current *WARP* with fn.  Note that fn is also a behavior.
  1377. ;; It is evaluated in the current environment first, then it is used to
  1378. ;; modify the environment seen by behavior.
  1379. ;; *WARP* is a triple: (d s f) denoting the function f(st+d).
  1380. ;; Letting g represent the new warp function fn, we want f(st+d) o g, or
  1381. ;; f(s*g(t) + d) in the form (d' s' f').
  1382. ;; Let's do this one step at a time:
  1383. ;; f(s*g(t) + d) = f(scale(s, g) + d)
  1384. ;;               = (shift f -d)(scale(s, g))
  1385. ;;               = (snd-compose (shift-time f (- d)) (scale s g))
  1386. ;;
  1387. ;; If f in NIL, it denotes the identity mapping f(t)=t, so we can
  1388. ;; simplify:
  1389. ;; f(scale(s, g) + d) = scale(s, g) + d
  1390. ;;                    = (snd-offset (scale s g) d)
  1391.  
  1392. (defmacro warp (x s)
  1393.  `(progv '(*WARP*) (list 
  1394.             (list 0.0 1.0
  1395.               (if (warp-function *WARP*)
  1396.                   (snd-compose (shift-time (warp-function *WARP*) 
  1397.                                (- (warp-time *WARP*)))
  1398.                        (scale (warp-stretch *WARP*) 
  1399.                           (must-be-sound ,x)))
  1400.                   (snd-offset (scale (warp-stretch *WARP*) 
  1401.                          (must-be-sound ,x))
  1402.                       (warp-time *WARP*)))))
  1403.      ,s))
  1404.  
  1405.  
  1406. (defmacro warp-abs (x s)
  1407.  `(progv '(*WARP*) (list (list 0.0 1.0 ,x))
  1408.      ,s))
  1409.  
  1410.  
  1411. ;; MULTICHAN-EXPAND -- construct and return array according to args
  1412. ;;
  1413. ;; arrays are used in Nyquist to represent multiple channels
  1414. ;; if any argument is an array, make sure all array arguments
  1415. ;; have the same length.  Then, construct a multichannel result
  1416. ;; by calling fn once for each channel.  The arguments passed to
  1417. ;; fn for the i'th channel are either the i'th element of an array
  1418. ;; argument, or just a copy of a non-array argument.
  1419. ;;
  1420. (defun multichan-expand (fn &rest args)
  1421.   (let (len newlen result) ; len is a flag as well as a count
  1422.     (dolist (a args)
  1423.         (cond ((arrayp a)
  1424.            (setf newlen (length a))
  1425.            (cond ((and len (/= len newlen))
  1426.               (error (format nil "In ~A, two arguments are vectors of differing length." fn))))
  1427.            (setf len newlen))))
  1428.     (cond (len
  1429.        (setf result (make-array len))
  1430.        ; for each channel, call fn with args
  1431.        (dotimes (i len)
  1432.            (setf (aref result i)
  1433.              (apply fn
  1434.             (mapcar
  1435.                 #'(lambda (a)
  1436.                 ; take i'th entry or replicate:
  1437.                 (cond ((arrayp a) (aref a i))
  1438.                       (t a)))
  1439.                 args))))
  1440.        result)
  1441.       (t
  1442.        (apply fn args)))))
  1443.  
  1444.  
  1445. ;; SELECT-IMPLEMENTATION-? -- apply an implementation according to args
  1446. ;;
  1447. ;; There is a different Nyquist primitive for each combination of 
  1448. ;; constant (NUMBERP) and time-variable (SOUNDP) arguments.  E.g.
  1449. ;; a filter with fixed parameters differs from one with varying
  1450. ;; parameters.  In most cases, the user just calls one function,
  1451. ;; and the arguments are decoded here:
  1452.  
  1453.  
  1454. ;; SELECT-IMPLEMENTATION-1-1 -- 1 sound arg, 1 selector
  1455. ;;
  1456. (defun select-implementation-1-1 (fns snd sel1 &rest others)
  1457.   (if (numberp sel1)
  1458.     (apply (aref fns 0) (cons snd (cons sel1 others)))
  1459.     (apply (aref fns 1) (cons snd (cons sel1 others)))))
  1460.  
  1461.  
  1462. ;; SELECT-IMPLEMENTATION-1-2 -- 1 sound arg, 2 selectors
  1463. ;;
  1464. ;; choose implemenation according to args 2 and 3
  1465. ;;
  1466. (defun select-implementation-1-2 (fns snd sel1 sel2 &rest others)
  1467.   (if (numberp sel2)
  1468.     (if (numberp sel1)
  1469.       (apply (aref fns 0) (cons snd (cons sel1 (cons sel2 others))))
  1470.       (apply (aref fns 1) (cons snd (cons sel1 (cons sel2 others)))))
  1471.     (if (numberp sel1)
  1472.       (apply (aref fns 2) (cons snd (cons sel1 (cons sel2 others))))
  1473.       (apply (aref fns 3) (cons snd (cons sel1 (cons sel2 others)))))))
  1474.  
  1475. ;; some waveforms
  1476.  
  1477. (setf *saw-table* (pwlvr -1 1 1))        ; eh, creepy way to get 2205 samples.
  1478. (setf *saw-table* (list *saw-table* (hz-to-step 1) T))
  1479.  
  1480. (setf *tri-table* (pwlvr -1 0.5 1 0.5 -1))
  1481. (setf *tri-table* (list *tri-table* (hz-to-step 1) T))
  1482.  
  1483. (setf *id-shape*  (pwlvr -1 2 1 .01 1))                ; identity
  1484. (setf *step-shape* (seq (const -1) (const 1 1.01)))  ; hard step at zero
  1485.  
  1486. (defun exp-dec (hold halfdec length)
  1487.   (let* ((target (expt 0.5 (/ length halfdec)))
  1488.      (expenv (pwev 1 hold 1 length target)))
  1489.     expenv)
  1490. )
  1491.  
  1492. ;;; operations on sounds
  1493.  
  1494. (defun diff (x y) (sum x (prod -1 y)))
  1495.  
  1496. ; compare-shape is a shape table -- origin 1.
  1497. (defun compare (x y &optional (compare-shape *step-shape*))
  1498.   (let ((xydiff (diff x y)))
  1499.     (shape xydiff compare-shape 1)))
  1500.  
  1501. ;;; oscs
  1502.  
  1503. (defun osc-saw (hz) (hzosc hz *saw-table*))
  1504. (defun osc-tri (hz) (hzosc hz *tri-table*))
  1505.  
  1506. ; bias is [-1, 1] pulse width.  sound or scalar.
  1507. ; hz is a sound or scalar
  1508. (defun osc-pulse (hz bias &optional (compare-shape *step-shape*))
  1509.   (compare bias (osc-tri hz) compare-shape))
  1510.  
  1511.  
  1512.